#include <iostream>
#include <string>
#include <memory>
#include "Socket.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Protocol.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " serverip serverport" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    Console();
    std::unique_ptr<Socket> sockptr = std::make_unique<TcpSocket>();
    sockptr->BuildClientSocketMethod();
    InetAddr serveraddr(serverport, serverip);
    if(sockptr->Connect(serveraddr))
    {
        LOG(LogLevel::INFO) << "申请连接成功";
        std::string inbuffer;
        while(true)
        {
            //构建请求
            Request req;
            std::cout << "Please Enter X: ";
            std::cin >> req._x;
            std::cout << "Please Enter Y: ";
            std::cin >> req._y;
            std::cout << "Please Enter Opertor: ";
            std::cin >> req._oper;

            //序列化
            std::string jsonstr;
            req.Serialize(&jsonstr);

            //封装报文
            std::string send_str = Protocol::Package(jsonstr);

            //发送给对端
            sockptr->Send(send_str);

            //接收对端发来的数据
            sockptr->Recv(&inbuffer);

            //报文解析
            std::string package;
            int n = Protocol::Unpack(inbuffer, &package);
            if(n > 0)
            {
                Response ret;
                //反序列化
                bool r = ret.Deserialize(package);
                if(r)
                {
                    ret.Print();//打印结果
                }
            }
        }
    }


    return 0;
}